package com.chengzheng.crawler.spiderman.work;

import com.chengzheng.crawler.spiderman.pojo.Task;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhengcheng
 * @date 2018/1/30
 * @time 下午5:40
 * @email chengzhengzheng@meituan.com
 **/

public abstract class WorkerManager implements Runnable {
    private int nWorkers;


    protected Worker worker;

    public WorkerManager(int size) {
        this.nWorkers = size > 0 ? size : 1;
    }

    @Override
    public void run() {
        List<Worker> workers = new ArrayList<>(nWorkers);
        for (int i = 0; i < nWorkers; i++) {
            final Worker work = this.buildWorker();
            work.setName(work.getThreadName() + "-" + i);
            workers.add(work);
        }

        workers.forEach(w -> w.start());

    }

    /**
     * 构建具体执行者
     *
     * @return
     */
    protected abstract Worker buildWorker();


    /**
     * 取出任务
     *
     * @return
     * @throws InterruptedException
     */
    public abstract Task takeTask() throws InterruptedException;

    public void done(WorkerResult workerResult) {
        this.handleResult(workerResult);
    }

    /**
     * 处理任务返回结果
     *
     * @param workerResult
     */
    protected abstract void handleResult(WorkerResult workerResult);
}
